package cn.fl.inscare.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import ins.car.facade.car.prj.api.InsOrPrjCombinationApiService;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.base.framework.utils.UploadUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.inscare.service.IInsUploadFileService;
import cn.fl.inscare.transform.SysUlFilesRecVOTransform;
import cn.fl.inscare.vo.FileAttrVO;
import cn.fl.inscare.vo.SysUlFilesRecVO;
import cn.fl.inscare.vo.UploadIdentityVO;
@Service
public class InsUploadFileServiceImpl implements IInsUploadFileService{
    private static final Logger logger = LoggerFactory.getLogger(InsUploadFileServiceImpl.class);

    @Autowired
    private InsOrPrjCombinationApiService insOrPrjCombinationApiService;
	@Autowired
	private IUploadApiService uploadApiService;
	
	/**
	 * 上传身份证
	 */
	@Override
	public boolean uploadIdentity(HttpServletRequest request,UploadIdentityVO uiVo) {
		 	String cfgCd = "INS006";
	        String rootPath = "insIdentity/";
	        String tableName = "INS_PER_IDENTITY";
	        uploadAttachment(request, uiVo.getApplyId(), rootPath, tableName, uiVo.getFileAttrs(), cfgCd, null, null, null);
	        return true;
	}

	/**
	 * 上传行驶证
	 */
	@Override
	public boolean uploadInsVehLice(HttpServletRequest request,
			UploadIdentityVO uiVo) {
		 	String cfgCd = "INS003";
	        String rootPath = "insVehicleLicense/";
	        String tableName = "INS_VEHICLE_LICENSE";
	        uploadAttachment(request, uiVo.getApplyId(), rootPath, tableName, uiVo.getFileAttrs(), cfgCd, null, null, null);
		return true;
	}
	/**
	 * 上传营业执照
	 */
	@Override
	public boolean uploadInsApplyBuss(HttpServletRequest request,
			UploadIdentityVO uiVo) {
		    String cfgCd ="INS005";
	        String rootPath = "insBusinessLicense/";
	        String tableName = "INS_BUSINESS_LICENSE";
	        uploadAttachment(request, uiVo.getApplyId(), rootPath, tableName, uiVo.getFileAttrs(), cfgCd, null, null, null);
		return true;
	}

	@Override
	public boolean uploadInsApply(HttpServletRequest request,UploadIdentityVO uiVo) {
		  	String cfgCd ="INS008";
	        String rootPath = "insInsurePolicy/";
	        String tableName = "INS_INSURE_POLICY";
	        uploadAttachment(request, uiVo.getApplyId(), rootPath, tableName, uiVo.getFileAttrs(), cfgCd, null, null, null);
	        return true;
	}

	 /**
     * 上传附件
     *
     * @param request
     * @param id        表主键，与附件相关联表的主键id
     * @param rootPath  根路径，例如：insvehiclelicense/
     * @param tableName 表名，与附件相关联表的
     * @param fileAttrs 文件属性集合，name:code 键值对
     * @param cfgCd     cfgCd 例如：行驶证主配置->INS003
     * @param sysCd     默认值：null，从ins.constant.facade.framework.constant.SystemConstant.INS_SERVICE_CD取，值为：17000
     * @param orgCd     默认值：null，从ins.constant.facade.framework.constant.SystemConstant.INS_USE_ORG_CD取，值为：0000
     * @param isDel     默认值：null，表示true，是否删除老的记录（数据库）,=true可以不传
     */
    private void uploadAttachment(HttpServletRequest request, Long id, String rootPath, String tableName, List<FileAttrVO> fileAttrs, String cfgCd, String sysCd, String orgCd, Boolean isDel) {
        if (StringUtils.isEmpty(sysCd)) {
            sysCd = "17000";
        }
        if (StringUtils.isEmpty(orgCd)) {
            orgCd = "0000";
        }
        if (isDel == null) {
            isDel = true;
        }
       // printParams(id, rootPath, tableName, fileAttrs, cfgCd, orgCd, isDel);
        checkParam(id, rootPath, tableName, fileAttrs, cfgCd, sysCd, orgCd, isDel);
        List<MultipartFile> multipartFiles = UploadUtils.getFileSet("files", request, null, null);
        if (CollectionUtils.isEmpty(multipartFiles)) {
            BaseLogUtils.info(logger, "uploadAttachment", "未获取到上传文件!");
            throw new BaseException("未获取到上传文件!");
        }

//        if (multipartFiles.size() != fileAttrs.size()) {
//            logger.info("上传文件数量：{}个；文件属性数量：{}个", multipartFiles.size(), fileAttrs.size());
//            throw new BaseException("上传文件的数量和文件属性的数量不匹配");
//        }
        //获上上传根目录、上传自定义目录、当前时间
        String currentTime = DateUtils.formatDateToString(new Date(), DateUtils.YYYYMMDD);
        //String validStatus = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_VALID_STATUS_CD_B);
        //系统相对 + 系统代码 + 模块 + 时间 + 文件
        String uploadRoot = PropertiesCacheUtils.getProperty("ulfiles.ulfiles.properties.ins.root.path");
        String customerPath = PropertiesCacheUtils.getProperty("ulfiles.ulfiles.properties.ins.costomer.path");
        if (StringUtils.isEmpty(uploadRoot)) {
            logger.info("'{}' 的配置为空", cmm.comm.facade.upload.constant.UploadConstant.UPLOAD_ROOT_PATH);
            throw new BaseException(String.format("'{}' 的配置为空", cmm.comm.facade.upload.constant.UploadConstant.UPLOAD_ROOT_PATH));
        }
        if (StringUtils.isEmpty(customerPath)) {
            logger.info("'{}' 的配置为空", cmm.comm.facade.upload.constant.UploadConstant.UPLOAD_COSTOMER_PATH);
            throw new BaseException(String.format("'{}' 的配置为空", cmm.comm.facade.upload.constant.UploadConstant.UPLOAD_COSTOMER_PATH));
        }
        String inputPath = null;
        String realPath = null;
        String fileName = null;
        String path = null;
        List<SysUlFilesRecVO> addList = new ArrayList<>();
        //保存附件信息
        for (MultipartFile multipartFile : multipartFiles) {
            //当前上传文件名
            fileName = multipartFile.getOriginalFilename();

            try {
               // printParams(multipartFile, uploadRoot, customerPath, rootPath, currentTime, fileName);
                inputPath = String.format("%s%s%s%s", uploadRoot, customerPath, rootPath, currentTime);
                BaseLogUtils.info(logger, "uploadAttachment", String.format("调用UploadUtils.uploadFile方法，第二个参数：path = %s", inputPath));
                realPath = UploadUtils.uploadFile(multipartFile, inputPath, fileName);
                BaseLogUtils.info(logger, "uploadAttachment", String.format("调用UploadUtils.uploadFile方法，返回的实际路径：realPath = %s", realPath));
                path = realPath.replace(uploadRoot, "");
            } catch (Exception e) {
                BaseLogUtils.error(logger, "uploadAttachment", "狮桥在线后台管理上传附件失败! fileName:" + fileName);
                BaseLogUtils.info(logger, "uploadAttachment", "狮桥在线后台管理上传附件异常!" + e.toString());
                BaseException be = new BaseException("狮桥在线后台管理上传图片失败!");
                be.initCause(e);
                throw be;
            }

            SysUlFilesRecVO entity = new SysUlFilesRecVO();
            entity.setFileNm(fileName);
            String cfgDtlCd = getCfgDtlCd(fileAttrs, multipartFile);
            entity.setSysCd(sysCd);
            entity.setOrgCd(orgCd);
            entity.setCfgCd(cfgCd);
            entity.setCfgDtlCd(cfgDtlCd);
            entity.setPkId(String.valueOf(id));
            entity.setTabNm(tableName);
            entity.setFilePath(path);
            entity.setIsDel(BaseConstant.IS_YESNO_NO);
            entity.setCrtTm(new Date());
            entity.setAbsLocPath(realPath);
           // entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            //entity.setAudStsCd(validStatus);
            addList.add(entity);
        }
        logger.info(addList.toString());
        if (CollectionUtils.isNotEmpty(addList)) {
            List<SysUlFilesRecDTO> listDto = SysUlFilesRecVOTransform.toDTOList(addList);
            Boolean flag = this.uploadApiService.addSysUlFilesRecListWithIsDel(listDto, isDel);
            if (flag) {
                BaseLogUtils.info(logger, "uploadAttachment", "狮桥在线后台管理上传图片成功");
                return;
            }

            throw new BaseException("狮桥在线后台管理上传图片失败!");
        }
    }
    
    /**
     * 校验参数
     *
     * @param id
     * @param rootPath
     * @param tableName
     * @param fileAttrs
     * @param cfgCd
     * @param sysCd
     * @param orgCd
     * @param isDel
     */
    private void checkParam(Long id, String rootPath, String tableName, List<FileAttrVO> fileAttrs, String cfgCd, String sysCd, String orgCd, Boolean isDel) {
        if (id == null || id <= 0) {
            throw new BaseException(String.format("上传附件，id = %s", id));
        }
        if (StringUtils.isEmpty(rootPath)) {
            throw new BaseException("上传附件，rootPath = null");
        }
        if (StringUtils.isEmpty(tableName)) {
            throw new BaseException("上传附件，tableName = null");
        }
        if (CollectionUtils.isEmpty(fileAttrs)) {
            throw new BaseException("上传附件，fileAttrs = null");
        }
        if (StringUtils.isEmpty(cfgCd)) {
            throw new BaseException("上传附件，cfgCd = null");
        }
        if (StringUtils.isEmpty(sysCd)) {
            throw new BaseException("上传附件，sysCd = null");
        }
        if (StringUtils.isEmpty(orgCd)) {
            throw new BaseException("上传附件，orgCd = null");
        }
        if (isDel == null) {
            throw new BaseException("上传附件，isDel = null");
        }
    }
    
    /**
     * 获取cfgDtlCd
     *
     * @param fileAttrs
     * @param multipartFile
     * @return
     */
    private String getCfgDtlCd(List<FileAttrVO> fileAttrs, MultipartFile multipartFile) {
        for (FileAttrVO fileAttr : fileAttrs) {
            if (fileAttr.getName().equals(multipartFile.getOriginalFilename())) {
                return fileAttr.getCode();
            }
        }
        //记录比较日志
        for (FileAttrVO fileAttr : fileAttrs) {
            //logger.info("fileAtrr: name = {}, code = {}; multipartFile.getName = {}", fileAttr.getName(), fileAttr.getCode(), multipartFile.getName());
        }
        throw new BaseException("获取cfgDtlCd失败");
    }

	
	
	

}
